import React from 'react';
import {  Button, Table, Form, Pagination } from 'antd';
import './index.less';
import axios from 'axios';
import Tips from '../Tips/index';
import { connect } from 'react-redux';
import statuscode from '../statuscode/index';
import Addpeer from './AddPeer/index.jsx';
import ExtendPeer from './extend/index.jsx';
import Bread from '../common/Bread/index';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

const chainCodeStatus = {
  1000: '创建中',
  1010: '创建成功',
  1020: '创建失败',
};
class peer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      page: ['10', '20', '30', '40', '50', '60', '70', '80', '90'],
      message: '',
      limit: 10,
      pagenum: 1,
      timeout: false,
      netWorkName: this.props.changeNetwork,
      addvisible: false,
      extendvisible: false
    };
  }
  columns = [
    {
      title: '节点名称',
      dataIndex: '节点名称',
      key: '节点名称',
    }, {
      title: '类型',
      dataIndex: '类型',
      key: '类型',
    }, {
      title: '地址',
      dataIndex: '地址',
      key: '地址',
    }, {
      title: '端口',
      dataIndex: '端口',
      key: '端口',
    }, {
      title: '状态',
      dataIndex: '状态',
      key: '状态',
    }, {
      title: '服务器类型',
      dataIndex: '服务器类型',
      key: '服务器类型',
    }, {
      title: '操作',
      key: '操作',
      width: 250,
      render: (text, record) => (
        <span className="controlnet" >
          <span className="chaincodespan" onClick={this.usepeer.bind(this, text, record)} >使用该节点</span>
          <span className="chaincodespan" onClick={this.stoppeer.bind(this, text, record)} >停用该节点</span>
          <span className="chaincodespan" onClick={this.extendpeer.bind(this, text, record)} >扩容</span>
        </span>
      ),
    }
  ];
  componentWillMount() {
    this.ismounted = true;
    this.getData();
  }
  componentWillUnmount() {
    this.ismounted = false;
  }

  handleChancel = () => {
    this.setState({
      addvisible: false,
    });
  }
  extendChancel = () => {
    this.setState({
      extendvisible: false,
    });
  }
  extendsubmit = (qq, values) => {
  }
  showModal = () => {
    setTimeout(() => {
      this.setState({
        addvisible: true,
        message: ''
      });
    });
    // var Token = localStorage.getItem("token");
    // var _this=this
    // this.setState({
    //   message: 'loading'
    // })
    // axios({
    //     method: 'get',
    //     url : '/api/customer/user/approval/verifyAuth?orgId='+this.props.changeOrgid,
    //     headers:{
    //         'Content-Type':'application/json',
    //         Authorization:Token
    //     },
    // })
    // .then(function (response) {
    // if(_this.ismounted){
    // var code = response.data.code
    // var message = statuscode[code]
    // if (code == 201) message = '您不是组织管理员'
    // _this.setState({
    // message: message
    // },()=>{
    // if(response.data.data&&_this.props.changeNetwork&&code==200) {
    // setTimeout(()=>{
    // _this.setState({
    // addvisible: true,
    // message:''
    // })
    // })
    // }
    // else if(!_this.props.changeNetwork){
    // _this.setState({
    // message:'请加入一个网络！'
    // },()=>{
    // setTimeout(() => {
    // _this.setState({
    // message: ''
    // })
    // }, 1000)
    // })
    // }else{
    // setTimeout(() => {
    // _this.setState({
    // message: ''
    // })
    // }, 1000)
    // }
    // });
  // }
    // })
    // .catch(function (error) {
    // console.log(error);
    // if(_this.ismounted){
    // _this.setState({
    // message: '请求失败，请刷新重试'
    // },()=>{
    // setTimeout(()=>{
    // _this.setState({
    //  message:''
    // })
    // },1000)
    // })
    // }
    // });
  }
  usepeer = (text, record) => {
  }
  stoppeer=(text, record) => {
  }
  extendpeer = (text, record) => {
    this.setState({
      extendvisible: true,
    });
  }
  componentWillReceiveProps(nextprops) {
    if (this.props.changeNetwork !== nextprops.changeNetwork) {
      this.getData(nextprops.changeNetwork);
    }
  }
  handleCreate = (qq, _this) => {
    const $this = this;
    _this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          message: 'loading',
          timeout: true
        });
        setTimeout(() => {
          this.setState({
            timeout: false
          });
        }, 5000);
        const Token = localStorage.getItem('token');
        var data = {
          'RequestType': 'InstallChainCodeReq',
          'ChannelId': 'mychannel',
          'FabricFlag': this.props.changeNetwork,
          'ChainCodeInfo': {
            'ChainCodeName': values.ChainCodeName,
            'ChainCodePath': qq.installPath,
            'ChainCodeVersion': qq.versionV,
            'ChainCodeArgs': [
              String(qq.installInit),
              String(qq.installValue1),
              String(qq.installValueNum1),
              String(qq.installValue2),
              String(qq.installValueNum2)
            ],
          },
          OrgId: this.props.changeOrgid
        };
        console.log(data);
        if (!qq.installValue1 || !qq.installValueNum1 || !qq.installValueNum2 || qq.installValueNum1 == 'undefined' || !qq.installValue2 || qq.installValueNum2 == 'undefined') {
          $this.setState({
            message: '请填全初始化数据'
          }, () => {
            setTimeout(() => {
              $this.setState({
                message: ''
              });
            }, 1000);
          });
        } else {
          axios.post('/api/block/chainCode/installAndInstantiateChaincode', data, {
            headers: {
              'Content-Type': 'application/json',
              Authorization: Token,
            }
          })
            .then(function (response) {
              if ($this.ismounted) {
                var data = JSON.parse(response.data.data);
                var code = data.code;
                if (statuscode[data.code] == undefined) code = 500;
                var message = statuscode[code];
                if (data.code == 2026) {
                  $this.setState({
                    message: '您不是管理员',
                  });
                  setTimeout(() => {
                    $this.setState({
                      message: ''
                    });
                  }, 1000);
                  return;
                }
                if (code == 200) {
                  $this.setState({
                    message: message,
                    visible: false,
                  });
                  setTimeout(() => {
                    $this.getData($this.props.changeNetwork);
                    $this.setState({
                      message: ''
                    });
                  }, 1000);
                } else {
                  $this.setState({
                    message: message,
                  });
                  setTimeout(() => {
                    $this.setState({
                      message: ''
                    });
                  }, 1000);
                }
              }
            })
            .catch(function (error) {
              console.log(error);
              if ($this.ismounted) {
                $this.setState({
                  message: '请求失败，请刷新重试'
                });
                setTimeout(() => {
                  $this.setState({
                    message: ''
                  });
                }, 1000);
              }
            });
        }
      } else {
        console.log('Received values of form: ', values);
      }
    });
  }


  onShowSizeChange=(current, pageSize) => {
    this.setState({ limit: pageSize, pagenum: current }, () => {
      this.getData(this.props.changeNetwork);
    });
  }
  addsubmit=(qq, value) => {
    console.log(qq, value);
  }

  onChange=(pageNumber) => {
    this.setState({ pagenum: pageNumber }, () => {
      this.getData(this.props.changeNetwork);
    });
  }
  getData = (Network = this.state.netWorkName) => {
    var _this = this;
    var Token = localStorage.getItem('token');

    if (!this.props.changeOrgid) return;
    this.setState({
      message: 'loading'
    });
    const $this = this;
    axios({
      method: 'get',
      url: 'api/block/chainCode/queryChainCodes',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: {
        // 'RequestType': 'QueryInstalledChainCodesReq',
        'networkName': Network,
        'channelId': 'mychannel',
        limit: this.state.limit,
        page: this.state.pagenum,
        orgId: this.props.changeOrgid
      }
    })
      .then(function (response) {
        if (_this.ismounted) {
          let data = [];
          var code = response.data.code;
          // if (statuscode[response.data.code] == undefined) code = 500
          var message = statuscode[code];
          _this.setState({
            message: message
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
          let responsedata = response.data.data.rows;
          responsedata && responsedata.forEach((e, i) => {
            data.push({
              '状态': chainCodeStatus[e.ChainCodeStatus],
              key: String(i),
              '节点名称': e.ChainCodeName,
              '类型': e.ChainCodeVersion,
              '地址': e.ChainCodeVersion,
              '端口': e.ChainCodeVersion,
              '服务器类型': e.ChainCodePath,
            });
          });
          $this.setState({
            data: data,
            totalnum: response.data.data.total,
            messgae: ''
          });
        }
      })
      .catch(function (error) {
        if (_this.ismounted) {
          var message = '请求失败，请刷新重试';
          if (error === []) message = '';
          _this.setState({
            message: message
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }

  render() {
    const { selectedRowKeys, selectStatus } = this.state;
    const rowSelection = {
      selectedRowKeys,
      type: 'radio',
      onChange: this.onSelectChange,
    };
    const ButtonType = selectStatus ? 'default' : 'primary';
    const disabled = selectStatus ? 'disabled' : '';
    return (
      <div>
        <Bread bread={['节点管理', ['节点管理', 'nenodeManaget']]} />
        {/* <div className="ChainCode_button"> */}
        <div className="index-buttons chaincodebuttons">
          <Button type="primary" onClick={this.showModal} disabled={this.props.changeOrgid ? false : true} >新建Peer节点</Button>
        </div>
        <Table
          // rowSelection={rowSelection}
          columns={this.columns}
          dataSource={this.state.data}
          bordered
          pagination={false}
        />
        <div className="page_foot">
          <span className="data_num">共{this.state.totalnum}条</span>
          <Pagination pageSizeOptions={this.state.page} className="page" showSizeChanger showQuickJumper onShowSizeChange={this.onShowSizeChange} defaultCurrent={1} total={this.state.totalnum} onChange={this.onChange} />
        </div>
        <Addpeer
          visible={this.state.addvisible}
          onCancel={this.handleChancel}
          addsubmit={this.addsubmit}
        />
        <ExtendPeer
          visible={this.state.extendvisible}
          onCancel={this.extendChancel}
          submit={this.extendsubmit}
        />
        <Tips message={this.state.message} />
      </div>
    );
  }
}

const Peer = Form.create()(peer);
export default connect((state) => {
  return { ...state };
})(Peer);
